﻿@using Microsoft.Extensions.Configuration
@using Microsoft.AspNetCore.Mvc.Localization
@model List<OpenReservation.Models.ReservationPlace>
@inject IViewLocalizer Localizer
@inject IConfiguration configuration
@{
    ViewBag.Title = Localizer["PageTitle"].Value;
}
@section styles{
    <link href="~/Content/jqueryui/jquery-ui.min.css" rel="stylesheet" />
    <style>
        .center-block {
            display: block;
            padding-top: 0.6em;
            margin-left: auto;
            margin-right: auto;
        }

        .container > .show-inline {
            display: inline-block;
        }

        section {
            display: none;
            margin: 0.4em auto;
            max-width: 24em;
        }

        ul {
            list-style: none;
        }

        .btn {
            display: none;
        }
    </style>
}
<div class="container center-block" ng-app="ReservationApp">
    <div class="container" ng-controller="ReservateCtrl">
        <form id="form1" name="form1">
            <section id="secActivityRoom" ng-class="{'show':step==0}">
                <p class="lead">@Localizer["ChoosePlaceSectionTitle"]</p>
                <div id="placesList">
                    @if (Model.Count > 0)
                    {
                        <ul>
                            @foreach (var place in Model)
                            {
                                <li>
                                    <label>
                                        <input type="radio" value="@place.PlaceId" ng-click="nextStep()" name="place" />@place.PlaceName
                                    </label>
                                </li>
                            }
                        </ul>
                    }
                </div>
            </section>

            <section id="secPickDate" ng-class="{'show':step==1}">
                <p class="lead">@Localizer["ChooseDateSectionTitle"]</p>
                <div id="datepicker"></div>
            </section>

            <section id="secPickTimePeriod" ng-class="{'show':step==2}">
                <p class="lead">@Localizer["ChoosePeriodsSectionTitle"]</p>
                <div>
                    <div ng-repeat="item in ReservationPeriods"><label><input type="checkbox" ng-disabled="!item.IsCanReservate" name="cbPeriod" data-periodIndex="{{item.PeriodIndex}}" title="{{item.PeriodDescription}}" />{{item.PeriodTitle}}</label></div>
                </div>
            </section>

            <section id="secFillPersonInfo" ng-class="{'show':step==3}">
                <p class="lead">@Localizer["PersonInfoSectionTitle"]</p>
                <div class="form" style="text-align: left; padding-left: 5em">
                    <div class="form-group">
                        <label for="txtUnit">@Localizer["ReservationUnit"]</label>
                        <input type="text" class="form-control" value="" ng-minlength="3" ng-maxlength="30" id="txtUnit" placeholder="@Localizer["ReservationUnit"]" required="required" />
                    </div>
                    <div class="form-group">
                        <label for="txtActivity">@Localizer["ReservationActivityContent"]</label>
                        <input type="text" class="form-control" value="" id="txtActivity" placeholder="@Localizer["ReservationActivityContent"]" required="required" />
                    </div>
                    <div class="form-group">
                        <label for="txtUsername">@Localizer["ReservationPersonName"]</label>
                        <input type="text" value="" class="form-control" id="txtUsername" required="required" placeholder="@Localizer["ReservationPersonName"]" />
                    </div>
                    <div class="form-group">
                        <label for="txtPhone">@Localizer["ReservationPersonPhone"]</label>
                        <input type="text" class="form-control" value="" id="txtPhone" placeholder="@Localizer["ReservationPersonPhone"]" required="required" />
                    </div>
                </div>
            </section>

            <section id="secConfirmInfo" ng-class="{'show':step==4}">
                <p class="lead">@Localizer["ConfirmInfoSectionTitle"]</p>
                <table class="table table-striped">
                    <tr>
                        <td>@Localizer["ReservationForDate"]</td>
                        <td>{{ reservationModel.ReservationForDate }}</td>
                    </tr>
                    <tr>
                        <td>@Localizer["ReservationPlace"]</td>
                        <td>{{ reservationModel.ReservationPlaceName }}</td>
                    </tr>
                    <tr>
                        <td>@Localizer["ReservationPeriods"]</td>
                        <td>{{ reservationModel.ReservationForTime }}</td>
                    </tr>
                    <tr>
                        <td>@Localizer["ReservationUnit"]</td>
                        <td>{{ reservationModel.ReservationUnit }}</td>
                    </tr>
                    <tr>
                        <td>@Localizer["ReservationActivityContent"]</td>
                        <td>{{ reservationModel.ReservationActivityContent }}</td>
                    </tr>
                    <tr>
                        <td>@Localizer["ReservationPersonName"]</td>
                        <td>{{ reservationModel.ReservationPersonName }}</td>
                    </tr>
                    <tr>
                        <td>@Localizer["ReservationPersonPhone"]</td>
                        <td>{{ reservationModel.ReservationPersonPhone }}</td>
                    </tr>
                </table>
                <div>
                    <span>@Localizer["ConfirmReservationInfoTip"]</span>
                    <button id="TencentCaptcha1" style="visibility:hidden;width:12rem;height:1rem"></button>
                </div>
            </section>
            <footer class="container">
                <button id="btnPreviousStep" ng-class="{'show-inline':step!=0}" type="button" ng-click="previousStep()" class="btn btn-default">@Localizer["PreviousStep"]</button>
                <button ng-click="nextStep()" type="button" class="btn btn-default" ng-class="{'show-inline':step!=4}" id="btnNext">@Localizer["NextStep"]</button>
                <button ng-click="submitForm()" type="button" ng-disabled="isSubmit" class="btn btn-default" ng-class="{'show-inline':step==4,'disabled':!isModelValid()}">@Localizer["Submit"]</button>
            </footer>
        </form>
    </div>
</div>
@section scripts{
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/jquery-ui.min.js"></script>
    <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
    <script>
        var phoneRegExp = /^1[3-9]\d{9}$/;
        var pNameRegExp = /^[\u4e00-\u9fa5]{2,4}$/;

        Date.prototype.addDays = function(number) {
            var adjustDate = new Date(this.getTime() + 24 * 60 * 60 * 1000 * number);
            return adjustDate;
        }

        $(function() {
            $("#datepicker").datepicker({
                dateFormat: "yy-mm-dd",
                minDate: new Date(),
                maxDate: new Date().addDays(7)
            });
            $("#datepicker").children("div").css("margin", "0 auto");
        });
        //angular
        angular.module("ReservationApp", [])
            .controller("ReservateCtrl",
                function($scope, $http) {
                    //model
                    $scope.reservationModel = {
                        ReservationUnit: "",
                        ReservationActivityContent: "",
                        ReservationPersonName: "",
                        ReservationPersonPhone: "",
                        ReservationPlaceId: "",
                        ReservationForDate: "",
                        ReservationForTime: "",
                        ReservationForTimeIds: "",
                        ReservationPlaceName: ""
                    };
                    //是否已经提交，避免客户端重复提交
                    $scope.isSubmit = false;
                    $scope.tCode = {
                        ticket: "",
                        nonce: ""
                    };
                    $scope.tencentRecaptcha = new TencentCaptcha(
                        document.getElementById('TencentCaptcha1'),
                        '@(configuration["Tencent:Captcha:AppId"])',
                        function(res) {
                            $scope.isCodeValid = false;

                            console.log(res);
                            // res（用户主动关闭验证码）= {ret: 2, ticket: null}
                            // res（验证成功） = {ret: 0, ticket: "String", randstr: "String"}
                            if (res.ret === 0) {
                                $scope.tCode.nonce = res.randstr;
                                $scope.tCode.ticket = res.ticket;
                                $scope.isCodeValid = true;
                                $scope.tencentRecaptcha.destroy();
                                // 验证通过自动提交预约信息
                                $scope.submitForm();
                            }
                        }
                    );
                    $scope.isCodeValid = false;
                    //判断数据是否通过验证
                    $scope.isModelValid = function() {
                        //所有属性均不能为空
                        for (var o in $scope.reservationModel) {
                            if ($scope.reservationModel) {
                                continue;
                            } else {
                                return false;
                            }
                        }
                        //特殊字段判断
                        //联系人姓名
                        if($scope.reservationModel.ReservationPersonName.length < 2 || $scope.reservationModel.ReservationPersonName.length > 16){
                            return false;
                        }
                        //联系方式
                        if (!$scope.reservationModel.ReservationPersonPhone.match(phoneRegExp)) {
                            return false;
                        }
                        return true;
                    }
                    //current step
                    $scope.step = 0;
                    $scope.ReservationPeriods = [];
                    //submit
                    $scope.submitForm = function() {
                        if (!$scope.isCodeValid) {
                            $scope.tencentRecaptcha.show(); // show tencent captcha
                            return;
                        }
                        $scope.isSubmit = true;
                        var loading = layer.load(2);
                        $http.post("/Home/MakeReservation",
                                $scope.reservationModel,
                                {
                                    headers: {
                                        "captchaType": "Tencent",
                                        "captcha": JSON.stringify($scope.tCode)
                                    }
                                })
                            .success(function(response) {
                                //console.log(response);
                                layer.close(loading);
                                if (response.Status == 200) {
                                    layer.msg('@Localizer["ReservationSuccessTip"]');
                                    location.href = "/";
                                } else {
                                    layer.msg(response.ErrorMsg);
                                    $scope.isSubmit = false;
                                }
                            })
                            .error(function(response) {
                                layer.close(loading);
                                layer.msg('@Localizer["ReservationFailedTip"]！');
                                $scope.isSubmit = false;
                            });
                    };
                    //next
                    $scope.nextStep = function() {
                        console.log(`current step: ${$scope.step}`);
                        switch ($scope.step) {
                        case 0:
                            //预约地点 判断
                            var place = $("input[name='place']:radio:checked").val();
                            if (place) {
                                $scope.reservationModel.ReservationPlaceId =
                                    $("input[name='place']:radio:checked").val();
                                $scope.reservationModel.ReservationPlaceName =
                                    $("input[name='place']:radio:checked").parent().text().trim();
                            } else {
                                layer.msg('@Localizer["ChoosePlaceTip"]');
                                return;
                            }
                            break;

                        case 1:
                            //预约日期判断处理
                            var date = $("#datepicker").val();
                            if (!date) {
                                layer.msg('@Localizer["ChooseDateTip"]');
                                return;
                            } else {
                                //TODO:从服务器端判断日期是否合法，不合法则提示用户重新选择
                                $scope.reservationModel.ReservationForDate = date;
                                //请求服务器端接口，判断可用预约时间段
                                var loading = layer.load(2);
                                $.ajax({
                                    url: `/api/ReservationPlaces/${$scope.reservationModel.ReservationPlaceId
                                        }/periods?placeId=${$scope.reservationModel.ReservationPlaceId
                                        }&dt=${$scope.reservationModel.ReservationForDate}`,
                                    type: "get",
                                    async: false,
                                    success: function(response) {
                                        if (response) {
                                            $scope.ReservationPeriods = response;
                                        }
                                        layer.close(loading);
                                    },
                                    beforeSend: function() {
                                        loading = layer.load(2);
                                    },
                                    error: function(res) {
                                        layer.close(loading);
                                        layer.alert(res);
                                    }
                                });
                            }
                            break;

                        case 2:
                            //预约时间段
                            var periods = [];
                            $("input:checkbox[name='cbPeriod']:checked").each(function(index, ele) {
                                periods.push(ele);
                            });
                            if (!periods || periods.length <= 0) {
                                layer.msg('@Localizer["ChooseReservationPeriodsTip"]');
                                return;
                            }
                            @* if (periods.length > 2) {
                                layer.msg('预约时间段不能超过两个');
                                return;
                            } *@
                            var tempPeriods = [], tempPeriodIds = [];
                            for (var i in periods) {
                                tempPeriodIds.push($(periods[i]).attr("data-periodIndex"));
                                tempPeriods.push($(periods[i]).parent().text());
                            }
                            $scope.reservationModel.ReservationForTimeIds = tempPeriodIds.join(",");
                            $scope.reservationModel.ReservationForTime = tempPeriods.join(',');
                            break;
                        case 3:
                            //预约人信息 判断
                            var pName = $("#txtUsername").val(),
                                pPhone = $("#txtPhone").val(),
                                unit = $("#txtUnit").val(),
                                activity = $("#txtActivity").val();

                            if (pPhone && pName && unit && activity) {
                                if(pName.length < 2 || pName.length > 16){
                                    layer.msg('@Localizer["InvalidPersonName"]');
                                    return;
                                }
                                if (!pPhone.match(phoneRegExp)) {
                                    layer.msg('@Localizer["InvalidPersonPhone"]');
                                    return;
                                }
                                $scope.reservationModel.ReservationUnit = unit;
                                $scope.reservationModel.ReservationActivityContent = activity;
                                $scope.reservationModel.ReservationPersonName = pName;
                                $scope.reservationModel.ReservationPersonPhone = pPhone;
                            } else {
                                layer.msg('@Localizer["InCompleteReservationInfo"]');
                                return;
                            }
                            break;
                        case 4:
                        default:
                            break;
                        }
                        //step
                        $scope.step = $scope.step + 1;
                    };
                    //previous
                    $scope.previousStep = function() {
                        $scope.step = $scope.step - 1;
                    };
                });
    </script>
}
